package com.eatme.web.app.coupon.settlement.executor.impl;

import com.eatme.web.app.coupon.settlement.constant.RuleFlag;
import com.eatme.web.app.coupon.settlement.executor.AbstractExecutor;
import com.eatme.web.app.coupon.settlement.executor.RuleExecutor;
import com.eatme.web.app.coupon.common.vo.CouponTemplateSDK;
import com.eatme.web.app.coupon.common.vo.SettlementInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Collections;

/**
 * 满减优惠结算规则执行器
 */
@Component
public class ManJianExecutor extends AbstractExecutor implements RuleExecutor {

    private static final Logger LOG = LoggerFactory.getLogger(ManJianExecutor.class);

    /**
     *  规则类型标记
     * @return
     */
    @Override
    public RuleFlag ruleConfig() {
        return RuleFlag.MANJIAN;
    }

    /**
     * 优惠券规则的计算
     * @param settlement {@link SettlementInfo} 包含了选择的优惠券
     * @return {@link SettlementInfo} 修正过的结算信息
     */
    @Override
    public SettlementInfo computeRule(SettlementInfo settlement) {
        Integer goodsSum = goodsCostSum(settlement.getGoodsInfos());
        SettlementInfo probability = processGoodsTypeNotSatisfy(settlement,goodsSum);

        if (null !=probability) {
            LOG.debug("ManJian Template Is Not Match To GoodsType!");
            return probability;
        }

        // 判断满减是否符合折扣标准
        CouponTemplateSDK templateSDK = settlement.getCouponAndTemplateInfos()
                .get(0).getTemplate();
        Integer base = templateSDK.getRule().getDiscount().getBase();
        Integer quota = templateSDK.getRule().getDiscount().getQuota();

        // 判断不符合标准,则直接返回商品总价
        if (goodsSum<base) {
            LOG.info("Current Goods Cost Sum < ManJian Coupon Base!");
            settlement.setCost(goodsSum);
            settlement.setCouponAndTemplateInfos(Collections.emptyList());
            return settlement;
        }

        // 计算使用优惠券之后的价格
        settlement.setCost((goodsSum-quota)>minCost()?(goodsSum-quota): minCost());
        LOG.debug("Use ManJian Coupon Make Goods Cost From {} To {}",goodsSum,settlement.getCost());

        return settlement;
    }
}
